<script setup>
import { ref, computed, watch } from 'vue';
import { Edit, Delete, Plus, Refresh } from '@element-plus/icons-vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';

const route = useRoute(); // 获取当前路由对象

// 路由对象
const router = useRouter();

// 教师列表数据
const teachers = ref([
    {
        "t_id": "T2023001",  // 工号
        "t_name": "王老师",   // 姓名
        "isAdmin": true      // 是否为管理员
    },
    {
        "t_id": "T2023002",
        "t_name": "李老师",
        "isAdmin": false
    },
    {
        "t_id": "T2023003",
        "t_name": "张老师",
        "isAdmin": false
    },
    {
        "t_id": "T2023004",
        "t_name": "刘老师",
        "isAdmin": true
    },
    {
        "t_id": "T2023005",
        "t_name": "陈老师",
        "isAdmin": false
    },
    {
        "t_id": "T2023006",
        "t_name": "赵老师",
        "isAdmin": false
    },
    {
        "t_id": "T2023007",
        "t_name": "孙老师",
        "isAdmin": true
    },
    {
        "t_id": "T2023008",
        "t_name": "周老师",
        "isAdmin": false
    },
    {
        "t_id": "T2023009",
        "t_name": "吴老师",
        "isAdmin": false
    },
    {
        "t_id": "T2023010",
        "t_name": "郑老师",
        "isAdmin": true
    }
]);


// 分页后的教师数据
const paginatedTeachers = computed(() => {
    const start = (pageNum.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    return teachers.value.slice(start, end);
});

// 教师数据模型
const teacherData = ref({
    t_id: null,   // 工号
    t_name: '',   // 姓名
    isAdmin: false // 是否为管理员
})

import { teacherListService, teacherSearchService, teacherAddService, teacherResetPasswordService, teacherUpdateService, teacherDeleteService } from '@/api/teacher.js'

// 声明一个异步的函数,获取某场考试的教师列表
const getTeacherList = async () => {
    try {
        let result = await teacherListService();
        teachers.value = result.data;
    } catch (error) {
        ElMessage.error('获取列表失败');
    }
}

// 调用查询
getTeacherList();

// 通过个人信息搜索教师
const searchTeacherByInformation = async (teacherData) => {
    try {
        let result = await teacherSearchService(teacherData.value);
        teachers.value = result.data;

        // 如果返回的是空数组
        if (teachers.value = []) {
            ElMessage.info('未检索到符合要求的教师信息');
        }

    } catch (error) {
        ElMessage.error('获取列表失败');
    }
    // 清空表单
    resetForm();
};

// 重置教师列表
const resetList = () => {
    resetForm();
    getTeacherList();
}

// 抽屉状态
const visibleDrawer = ref(false);

// 触发抽屉时是否为编辑教师信息。
const isEditing = ref(false);

// 点击新增考试打开抽屉
const openDrawer = () => {
    visibleDrawer.value = true;
    isEditing.value = false;
    resetForm();
};

// 关闭抽屉
const closeDrawer = () => {
    visibleDrawer.value = false;
    resetForm();
};

// 清空教师数据模型的表单
const resetForm = () => {
    teacherData.value = {
        t_id: '',
        t_name: '',
        isAdmin: false,
    };
};

// 按下抽屉中“保存”键后，根据情景不同调用相关函数
const handleSubmit = () => {
    isEditing.value ? updateTeacher() : addTeacher();
};

// 添加教师
const addTeacher = async () => {
    if (!teacherData.value.t_id || !teacherData.value.t_name) {
        ElMessage.warning('请完整填写教师信息');
        return;
    }
    try {
        let result = await teacherAddService(teacherData.value);
        // 根据服务端返回的msg信息是否为空，判断是否添加成功
        ElMessage.success(result.msg ? result.msg : '教师已添加');

    } catch (error) {
        ElMessage.error('添加教师请求超时');
    }
    // 刷新教师列表
    getTeacherList();
    closeDrawer();
};


// 删除教师
const deleteTeacher = (id) => {
    ElMessageBox.confirm('确定要删除此教师吗？', '提示', {
        type: 'warning',
    }).then(async () => {
        try {
            let result = await teacherDeleteService(id);
            // 根据服务端返回的msg信息是否为空，判断是否删除成功
            ElMessage.success(result.msg ? result.msg : '删除成功');
            // 刷新教师列表
            getTeacherList();
        } catch (error) {
            ElMessage.error('删除请求超时');
        }
    });
};

// 修改教师信息（主要是姓名和管理员权限）
const editTeacher = (row) => {
    isEditing.value = true;
    visibleDrawer.value = true;
    teacherData.value = { ...row }; // 填充数据
};

// 重置教师密码 （默认密码：123456）
const resetTeacherPassword = (id) => {

    ElMessageBox.confirm('确定要重置密码？', '提示', {
        type: 'warning',
    }).then(async () => {
        try {
            // 调用教师信息修改接口
            let result = await teacherResetPasswordService(id);
            // 根据服务端返回的msg信息是否为空，判断是否更新成功
            ElMessage.success(result.msg ? result.msg : '教师密码已重置');
            // 刷新教师列表
            getTeacherList();
        } catch (error) {
            ElMessage.error('重置密码请求超时');
        }
    });

}

// 更新信息
const updateTeacher = async () => {
    try {
        // 调用教师信息修改接口
        let result = await teacherUpdateService(teacherData.value);
        // 根据服务端返回的msg信息是否为空，判断是否更新成功
        ElMessage.success(result.msg ? result.msg : '教师信息已更新');
        // 刷新教师列表
        getTeacherList();
    } catch (error) {
        ElMessage.error('教师信息编辑请求超时');
    }
    closeDrawer();
};


// 页面具体数据信息
const pageNum = ref(1); // 当前页
const pageSize = ref(3); // 每页条数
const total = ref(teachers.value.length); // 总条数

// 页大小改变
const onSizeChange = (size) => {
    pageSize.value = size;
    pageNum.value = 1; // 重置到第一页
};

// 页码改变
const onPageChange = (page) => {
    pageNum.value = page;
};

// 监听 teachers 数组变化，实时更新 total 值
watch(
    () => teachers.value,
    (newVal) => {
        total.value = newVal.length;
    },
    { deep: true }
);

</script>


<template>
    <el-card>
        <template #header>
            <div class="header">
                <!-- <el-button type="primary" @click="goBack()">返回</el-button> -->

                <h1>{{ '教师管理' }}</h1>

                <el-button type="primary" @click="openDrawer()">添加教师</el-button>
            </div>
        </template>

        <h1>{{ teacherData }}</h1>
        <!-- 搜索表单 -->
        <el-form inline :model="teacherData">
            <el-form-item label="工号">
                <el-input v-model="teacherData.t_id" placeholder="请输入学号" />
            </el-form-item>
            <el-form-item label="姓名">
                <el-input v-model="teacherData.t_name" placeholder="请输入姓名" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="searchTeacherByInformation(teacherData)">搜索</el-button>
                <el-button @click="resetList()">重置</el-button>
            </el-form-item>
        </el-form>
        <br>

        <!-- 教师表格 -->
        <el-table :data="paginatedTeachers" style="width: 100%">
            <el-table-column label="工号" prop="t_id"></el-table-column>
            <el-table-column label="姓名">
                <template #default="{ row }">
                    {{ row.t_name }}
                </template>
            </el-table-column>
            <el-table-column label="是否为管理员">
                <template #default="{ row }">
                    {{ row.isAdmin }}
                </template>
            </el-table-column>

            <el-table-column label="操作">
                <template #default="{ row }">
                    <el-tooltip content="修改教师" placement="top">
                        <el-button :icon="Edit" circle plain type="primary" @click="editTeacher(row)"></el-button>
                    </el-tooltip>
                    <el-tooltip content="重置密码" placement="top">
                        <el-button :icon="Refresh" circle plain type="primary"
                            @click="resetTeacherPassword(row.t_id)"></el-button>
                    </el-tooltip>
                    <el-tooltip content="删除教师" placement="top">
                        <el-button :icon="Delete" circle plain type="danger"
                            @click="deleteTeacher(row.t_id)"></el-button>
                    </el-tooltip>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页条   5555-->
        <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5, 10, 15]"
            layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
            @current-change="onPageChange" style="margin-top: 20px; justify-content: flex-end" />


        <!-- 添加/编辑教师的抽屉 -->
        <el-drawer v-model="visibleDrawer" :title="isEditing ? '编辑教师' : '添加教师'" size="30%">
            <el-form :model="teacherData" label-width="80px">
                <el-form-item label="工号">
                    <el-input v-model="teacherData.t_id" placeholder="请输入工号" :disabled="isEditing" />
                </el-form-item>
                <el-form-item label="姓名">
                    <el-input v-model="teacherData.t_name" placeholder="请输入姓名" />
                </el-form-item>
                <el-form-item label="权限:">
                    <el-select placeholder="请选择" v-model="teacherData.isAdmin" @change="teacherData.isAdmin">
                        <el-option label="非管理员" :value=false></el-option>
                        <el-option label="管理员" :value=true></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSubmit">保存</el-button>
                    <el-button @click="closeDrawer">取消</el-button>
                </el-form-item>
            </el-form>
        </el-drawer>
    </el-card>
</template>


<style scoped>
.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.upload-demo {
    margin: 10px 0;
}
</style>
